<template>
    <div class="article-edit">
        <el-card class="!border-none" shadow="never">
            <el-page-header
                :content="route.query.id ? '编辑banner' : '添加banner'"
                @back="$router.back()"
            />
        </el-card>
        <el-card class="mt-4 !border-none" shadow="never">
            <el-form
                class="ls-form"
                label-width="85px"
                :model="formData"
                :rules="rules"
                ref="formRef"
            >
                <div class="xl:flex">
                    <div>
                        <el-form-item label="banner图" prop="img">
                            <div>
                                <el-upload
                                    class="avatar-uploader"
                                    ref="uploadRefs"
                                    :on-change="onChange"
                                    v-loading="loading"
                                    :show-file-list="false"
                                    :auto-upload="false"
                                >
                                    <div class="up-box" v-if="formData.img == ''">
                                        <el-icon color="#606266" :size="20">
                                            <Plus />
                                        </el-icon>
                                    </div>
                                    <img v-else :src="formData.img" class="avatar" />
                                </el-upload>
                            </div>
                        </el-form-item>

                        <el-form-item label="状态" prop="status" required>
                            <el-radio-group v-model="formData.status">
                                <el-radio :label="1">启用</el-radio>
                                <el-radio :label="2">禁用</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="排序" prop="sort">
                            <div class="w-[245px]">
                                <el-input
                                    :min="0"
                                    :max="9999"
                                    v-model="formData.sort"
                                    placeholder="请输入商品排序内容"
                                />
                                <text style="color: #a8abb2">数字越小越靠前</text>
                            </div>
                        </el-form-item>
                    </div>
                </div>
            </el-form>
        </el-card>
        <footer-btns>
            <el-button type="primary" @click="appendbanner">保存</el-button>
        </footer-btns>
    </div>
</template>

<script lang="ts" setup name="articleListsEdit">
import { ref } from 'vue'
import { fpFile } from '@/api/fpUpLoad'
import { bannerDetail, bannerEdit, add } from '@/api/banner'
import useMultipleTabs from '@/hooks/useMultipleTabs'
import type { FormInstance, FormRules } from 'element-plus'
const formRef = shallowRef<FormInstance>()
const { removeTab } = useMultipleTabs()
const route = useRoute()
const router = useRouter()
const loading = ref()
const rules = reactive<FormRules>({
    img: [{ required: true, message: '请上传banner图', trigger: ['blur', 'change'] }],
    sort: [{ required: true, message: '请输入排序', trigger: 'blur' }]
})
//下拉选择器模拟数据
const subcategoryss = []
//公用数据
const formData = reactive({
    banner: '',
    img: '',
    status: 1,
    sort: '100',
    banner_id: route.query.id
})

const listArr = ref([])
// 选择文件
const onChange = (file: any) => {
    //   console.log("文件信息:", file);
    listArr.value = []
    // 假设1024一片，可根据实际来进行，也可以调接口进行
    const count = Math.ceil(file.size / 1024 / 1024 / 5)
    // 拿文件后缀
    const suffix = file.name.substring(file.name.lastIndexOf('.') + 1)
    const chunkid = generateUUID()
    for (let i = 0; i < count; i++) {
        const item = new FormData()
        item.append('chunkindex', i) //当前是第几片
        item.append('chunkcount', count) //分片的总数量
        item.append('files', file.raw.slice(i * 1024 * 1024 * 5, (i + 1) * 1024 * 1024 * 5)) //文件流数据
        item.append('extension', suffix) //文件的后缀
        item.append('name', file.name) //文件名
        item.append('size', file.size) //文件大小
        item.append('mime', file.raw.type) //文件的mime类型
        item.append('chunkid', chunkid) //文件uid，选的每个文件不一样，做区分（不是每个分片的）
        item.append('key', 'iNWxBywRQMn3bXZ8E5OGszoAVIjL9P') //上传接口需要的key，不是固定写死的，根据后端修改调整
        listArr.value.push(item)
    }
    loading.value = true
    file_up()
}

const generateUUID = () => {
    let d = new Date().getTime()
    if (window.performance && typeof window.performance.now === 'function') {
        d += performance.now()
    }
    const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
        const r = (d + Math.random() * 16) % 16 | 0
        d = Math.floor(d / 16)
        return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16)
    })
    return uuid
}

// 走上传接口
const file_up = async () => {
    let video_index = 0
    for (const v of listArr.value) {
        video_index++
        const res = await fpFile(v)
        if (video_index == listArr.value.length) {
            formData.banner = res.save_url
            formData.img = res.show_url
        }
    }
    loading.value = false
}

// 获取详情
const getbannerinfo = async () => {
    const data = await bannerDetail({
        banner_id: route.query.id
    })
    Object.keys(formData).forEach((key) => {
        //@ts-ignore
        formData[key] = data[key]
        // 获取资质转换数据格式
        formData.img = data.banner_url
    })
}
//保存添加
const appendbanner = async () => {
    // 表单判断,走接口
    await formRef.value?.validate()
    if (route.query.id) {
        await bannerEdit(formData)
    } else {
        await add(formData)
    }
    removeTab()
    router.back()
}
route.query.id && getbannerinfo()
</script>
<style scoped>
.avatar {
    width: 130px;
    height: 130px;
}

.up-box {
    width: 130px;
    height: 130px;
    border-radius: 6px;
    border: 1px dashed #c0c4cc;
    display: flex;
    justify-content: space-around;
    align-items: center;
}
</style>
